package com.agrimall.servlet.client;

import com.agrimall.entity.Order;
import com.agrimall.entity.User;
import com.agrimall.service.OrderService;
import com.agrimall.service.UserService;
import com.agrimall.service.impl.OrderServiceImpl;
import com.agrimall.service.impl.UserServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 客户端订单管理Servlet
 */
@WebServlet("/client/order")
public class OrderServlet extends HttpServlet {
    private OrderService orderService = new OrderServiceImpl();
    private UserService userService = new UserServiceImpl();
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        
        if (user == null) {
            response.sendRedirect(request.getContextPath() + "/login.jsp");
            return;
        }
        
        String action = request.getParameter("action");
        
        if (action == null || action.equals("") || action.equals("list")) {
            // 订单列表
            listOrders(request, response, user);
        } else if (action.equals("detail")) {
            // 订单详情
            orderDetail(request, response, user);
        } else if (action.equals("pay")) {
            // 支付订单
            payOrder(request, response, user);
        } else if (action.equals("cancel")) {
            // 取消订单
            cancelOrder(request, response, user);
        } else if (action.equals("confirm")) {
            // 确认收货
            confirmReceipt(request, response, user);
        } else if (action.equals("json")) {
            // 获取订单JSON数据
            getOrderJson(request, response, user);
        } else {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        }
    }
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        
        if (user == null) {
            response.sendRedirect(request.getContextPath() + "/login.jsp");
            return;
        }
        
        String action = request.getParameter("action");
        
        if (action != null && action.equals("applyAfterSale")) {
            // 申请售后
            applyAfterSale(request, response, user);
        } else {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        }
    }
    
    /**
     * 订单列表
     */
    private void listOrders(HttpServletRequest request, HttpServletResponse response, User user)
            throws ServletException, IOException {
        String pageStr = request.getParameter("page");
        int page = 1;
        if (pageStr != null && !pageStr.isEmpty()) {
            try {
                page = Integer.parseInt(pageStr);
            } catch (NumberFormatException e) {
                page = 1;
            }
        }
        int pageSize = 10;
        
        List<Order> orders = orderService.getOrderListByUser(user.getUserId(), page, pageSize);
        int totalCount = orderService.countOrdersByUser(user.getUserId());
        
        int totalPages = (int) Math.ceil((double) totalCount / pageSize);
        if (totalPages == 0) {
            totalPages = 1;
        }
        
        boolean hasNextPage = page < totalPages;
        
        request.setAttribute("orders", orders);
        request.setAttribute("page", page);
        request.setAttribute("totalCount", totalCount);
        request.setAttribute("totalPages", totalPages);
        request.setAttribute("hasNextPage", hasNextPage);
        request.getRequestDispatcher("/client/order/list.jsp").forward(request, response);
    }
    
    /**
     * 订单详情
     */
    private void orderDetail(HttpServletRequest request, HttpServletResponse response, User user)
            throws ServletException, IOException {
        String orderIdStr = request.getParameter("orderId");
        if (orderIdStr == null) {
            response.sendRedirect(request.getContextPath() + "/client/order?action=list");
            return;
        }
        
        try {
            Long orderId = Long.parseLong(orderIdStr);
            Order order = orderService.getOrderById(orderId);
            
            if (order == null || !order.getUserId().equals(user.getUserId())) {
                response.sendRedirect(request.getContextPath() + "/client/order?action=list");
                return;
            }
            
            request.setAttribute("order", order);
            request.getRequestDispatcher("/client/order/detail.jsp").forward(request, response);
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("error", "数据加载失败：" + e.getMessage());
            request.getRequestDispatcher("/client/order/list.jsp").forward(request, response);
        }
    }
    
    /**
     * 支付订单
     */
    private void payOrder(HttpServletRequest request, HttpServletResponse response, User user)
            throws ServletException, IOException {
        response.setCharacterEncoding("UTF-8");
        
        String orderIdStr = request.getParameter("orderId");
        if (orderIdStr == null) {
            response.sendRedirect(request.getContextPath() + "/client/order?action=list");
            return;
        }
        
        try {
            Long orderId = Long.parseLong(orderIdStr);
            Order order = orderService.getOrderById(orderId);
            
            if (order == null || !order.getUserId().equals(user.getUserId())) {
                response.sendRedirect(request.getContextPath() + "/client/order?action=list");
                return;
            }
            
            String paymentMethod = request.getParameter("paymentMethod");
            if (paymentMethod == null || paymentMethod.isEmpty()) {
                paymentMethod = "余额支付";
            }
            
            boolean success = orderService.payOrder(order.getOrderNo(), paymentMethod);
            if (success) {
                User updatedUser = userService.getUserById(user.getUserId());
                if (updatedUser != null) {
                    request.getSession().setAttribute("user", updatedUser);
                }
                String message = URLEncoder.encode("支付成功", StandardCharsets.UTF_8.toString());
                response.sendRedirect(request.getContextPath() + "/client/order?action=list&message=" + message);
            } else {
                String error = URLEncoder.encode("支付失败，余额不足或订单状态异常", StandardCharsets.UTF_8.toString());
                response.sendRedirect(request.getContextPath() + "/client/order?action=list&error=" + error);
            }
        } catch (Exception e) {
            e.printStackTrace();
            String error = URLEncoder.encode("支付失败", StandardCharsets.UTF_8.toString());
            response.sendRedirect(request.getContextPath() + "/client/order/list?error=" + error);
        }
    }
    
    /**
     * 取消订单
     */
    private void cancelOrder(HttpServletRequest request, HttpServletResponse response, User user)
            throws ServletException, IOException {
        response.setCharacterEncoding("UTF-8");
        
        String orderIdStr = request.getParameter("orderId");
        if (orderIdStr == null) {
            response.sendRedirect(request.getContextPath() + "/client/order?action=list");
            return;
        }
        
        try {
            Long orderId = Long.parseLong(orderIdStr);
            Order order = orderService.getOrderById(orderId);
            
            if (order == null || !order.getUserId().equals(user.getUserId())) {
                response.sendRedirect(request.getContextPath() + "/client/order?action=list");
                return;
            }
            
            boolean success = orderService.cancelOrder(orderId);
            if (success) {
                String message = URLEncoder.encode("订单已取消", StandardCharsets.UTF_8.toString());
                response.sendRedirect(request.getContextPath() + "/client/order?action=list&message=" + message);
            } else {
                String error = URLEncoder.encode("取消失败，订单状态不允许取消", StandardCharsets.UTF_8.toString());
                response.sendRedirect(request.getContextPath() + "/client/order?action=list&error=" + error);
            }
        } catch (Exception e) {
            e.printStackTrace();
            String error = URLEncoder.encode("取消失败：" + e.getMessage(), StandardCharsets.UTF_8.toString());
            response.sendRedirect(request.getContextPath() + "/client/order/list?error=" + error);
        }
    }
    
    /**
     * 确认收货
     */
    private void confirmReceipt(HttpServletRequest request, HttpServletResponse response, User user)
            throws ServletException, IOException {
        response.setCharacterEncoding("UTF-8");
        
        String orderIdStr = request.getParameter("orderId");
        if (orderIdStr == null) {
            response.sendRedirect(request.getContextPath() + "/client/order?action=list");
            return;
        }
        
        try {
            Long orderId = Long.parseLong(orderIdStr);
            Order order = orderService.getOrderById(orderId);
            
            if (order == null || !order.getUserId().equals(user.getUserId())) {
                response.sendRedirect(request.getContextPath() + "/client/order?action=list");
                return;
            }
            
            boolean success = orderService.confirmReceipt(orderId);
            if (success) {
                String message = URLEncoder.encode("确认收货成功", StandardCharsets.UTF_8.toString());
                response.sendRedirect(request.getContextPath() + "/client/order?action=list&message=" + message);
            } else {
                String error = URLEncoder.encode("确认收货失败，订单状态异常", StandardCharsets.UTF_8.toString());
                response.sendRedirect(request.getContextPath() + "/client/order?action=list&error=" + error);
            }
        } catch (Exception e) {
            e.printStackTrace();
            String error = URLEncoder.encode("确认收货失败", StandardCharsets.UTF_8.toString());
            response.sendRedirect(request.getContextPath() + "/client/order/list?error=" + error);
        }
    }
    
    /**
     * 获取订单JSON数据
     */
    private void getOrderJson(HttpServletRequest request, HttpServletResponse response, User user)
            throws ServletException, IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        
        String orderIdStr = request.getParameter("orderId");
        if (orderIdStr == null) {
            out.print("{\"success\":false,\"message\":\"参数错误\"}");
            return;
        }
        
        try {
            Long orderId = Long.parseLong(orderIdStr);
            Order order = orderService.getOrderById(orderId);
            
            if (order == null || !order.getUserId().equals(user.getUserId())) {
                out.print("{\"success\":false,\"message\":\"订单不存在\"}");
                return;
            }
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("orderId", order.getOrderId());
            result.put("orderNo", order.getOrderNo());
            
            if (order.getOrderItems() != null) {
                List<Map<String, Object>> items = new java.util.ArrayList<>();
                for (com.agrimall.entity.OrderItem item : order.getOrderItems()) {
                    Map<String, Object> itemMap = new HashMap<>();
                    itemMap.put("productId", item.getProductId());
                    itemMap.put("productName", item.getProductName());
                    items.add(itemMap);
                }
                result.put("items", items);
            }
            
            ObjectMapper mapper = new ObjectMapper();
            out.print(mapper.writeValueAsString(result));
        } catch (Exception e) {
            e.printStackTrace();
            out.print("{\"success\":false,\"message\":\"服务器错误\"}");
        }
    }
    
    /**
     * 申请售后
     */
    private void applyAfterSale(HttpServletRequest request, HttpServletResponse response, User user)
            throws ServletException, IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        
        String orderIdStr = request.getParameter("orderId");
        if (orderIdStr == null) {
            out.print("{\"success\":false,\"message\":\"参数错误\"}");
            return;
        }
        
        try {
            Long orderId = Long.parseLong(orderIdStr);
            Order order = orderService.getOrderById(orderId);
            
            if (order == null || !order.getUserId().equals(user.getUserId())) {
                out.print("{\"success\":false,\"message\":\"订单不存在或无权操作\"}");
                return;
            }
            
            if (order.getStatus() != 3) {
                out.print("{\"success\":false,\"message\":\"只有已完成的订单才能申请售后\"}");
                return;
            }
            
            boolean success = orderService.applyAfterSale(orderId);
            if (success) {
                out.print("{\"success\":true,\"message\":\"申请售后成功\"}");
            } else {
                out.print("{\"success\":false,\"message\":\"申请售后失败\"}");
            }
        } catch (Exception e) {
            e.printStackTrace();
            out.print("{\"success\":false,\"message\":\"申请售后失败：" + e.getMessage() + "\"}");
        }
    }
}

